package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.util.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

/**
 * Created by songtie on 2015/4/27.
 */
public class UpdateCartQuantitiesServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private Cart cart;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");

        Iterator<CartItem> cartItems = cart.getAllCartItems();
        System.out.println(cart.getNumberOfItems());
        System.out.println(cartItems);

        while (cartItems.hasNext()) {
            System.out.println(7);
            CartItem cartItem = cartItems.next();
            System.out.println(8);
            String itemId = cartItem.getItem().getItemId();
            try {
                System.out.println(1);
                System.out.println("itemId: " + itemId);
                System.out.println("requestitemId: " + request.getParameter(itemId));
                int quantity = Integer.parseInt(request.getParameter(itemId));
                System.out.println(2);
                cart.setQuantityByItemId(itemId, quantity);
                System.out.println(3);
                if (quantity < 1) {
                    System.out.println(4);
                    cartItems.remove();
                }
            } catch (Exception e) {
                System.out.println(5);
                session.setAttribute("message", "The Quantities of Item must be Integer!");

                System.out.println(6);
//                request.getRequestDispatcher(ERROR).forward(request, response);

                System.out.println();
            }
        }


        //request.getRequestDispatcher(VIEW_CART).forward(request, response);

        //ajax请求的响应内容
        response.setContentType("text/json");
        PrintWriter out = response.getWriter();

        Result result = new Result();

        result.setMsg("ajax响应成功");

        String rt = JSON.toJSONString(result);

        out.print(rt);

        out.flush();
        out.close();
    }
}
